/*******************************************************************************
 * Copyright 2011, 2012 Chris Banes.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.common.handmark.pulltorefresh.library;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.common.dongqiuhui.apps.comm.tools.BallLog;
import com.common.handmark.pulltorefresh.library.internal.EmptyViewMethodAccessor;
import com.common.handmark.pulltorefresh.library.internal.LoadMoreLayout;
import com.common.handmark.pulltorefresh.library.internal.LoadingLayout;

import width.hgk.wanwan.R;

public class PullToRefreshLocationListView extends PullToRefreshAdapterViewBase<ListView> {

    private static final String TAG = PullToRefreshListView.class.getSimpleName();

    private LoadingLayout mHeaderLoadingView;
    private LoadingLayout mFooterLoadingView;

    private FrameLayout mLvFooterLoadingFrame;

    private boolean mListViewExtrasEnabled;

    public PullToRefreshLocationListView(Context context) {
        super(context);
        init();
    }

    public PullToRefreshLocationListView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public PullToRefreshLocationListView(Context context, Mode mode) {
        super(context, mode);
        init();
    }

    public PullToRefreshLocationListView(Context context, Mode mode, AnimationStyle style) {
        super(context, mode, style);
        init();
    }

    public static interface OnLoadMoreListener {
        public void onLoadMore();
    }

    /**
     * 加载更多方式
     * AUTO 自动
     * MANUAL 手动
     */
    public static enum EventSource {
        AUTO,
        MANUAL;
    }

    /**
     * 上下拉方式
     * AUTO 自动加载更多模式
     * MANUAL 上拉加载更多模式
     */
    public static enum PullStyle {
        AUTO,
        MANUAL;
    }

    private LoadMoreLayout loadMoreLayout;
    private OnLoadMoreListener onLoadMoreListener;

    private void init() {
        loadMoreLayout = new LoadMoreLayout(getContext());
        loadMoreLayout.showDivider(false);
        getRefreshableView().addFooterView(loadMoreLayout);

        loadMoreLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onLoadMoreListener != null) {
                    onLoadMoreListener.onLoadMore();
                }
            }
        });
        setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                PullToRefreshLocationListView.this.onLoadMore();
            }
        });

        setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                PullToRefreshLocationListView.this.onLoadMore();
            }
        });
    }

    public void onLoadMore() {
        BallLog.i(TAG, "onLoadMore getState[" + loadMoreLayout.getState() + "] mOnRefreshListener2[" + mOnRefreshListener2 + "]");
        if (loadMoreLayout.getState() != LoadMoreLayout.State.STATE_LOADING
                && loadMoreLayout.getState() != LoadMoreLayout.State.STATE_NO_DATA) {
            setLoadingMore();
            if (null != mOnRefreshListener2) {
                mOnRefreshListener2.onPullUpToRefresh(this);
            }
        }
    }

    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        onLoadMoreListener = listener;
    }

    @Override
    public void setMode(Mode mode) {
        setMode(mode, PullStyle.AUTO);
    }

    public void setMode(Mode mode, PullStyle pullStyle) {
        switch (mode) {
            case BOTH:
                if (pullStyle == PullStyle.MANUAL) {
                    super.setMode(Mode.BOTH);
                    removeFootView();
                    removeFootListener();
                } else if (pullStyle == PullStyle.AUTO) {
                    addFootView();
                    super.setMode(Mode.PULL_FROM_START);
                }
                break;
            case PULL_FROM_START:
                super.setMode(Mode.PULL_FROM_START);
                removeFootView();
                removeFootListener();
                break;
            case PULL_FROM_END:
                if (pullStyle == PullStyle.MANUAL) {
                    super.setMode(Mode.PULL_FROM_END);
                    removeFootView();
                    removeFootListener();
                } else if (pullStyle == PullStyle.AUTO) {
                    addFootView();
                    super.setMode(Mode.DISABLED);
                }
                break;
            case DISABLED:
                super.setMode(Mode.DISABLED);
                removeFootView();
                removeFootListener();
                break;
            default:
                break;
        }
        if (PullStyle.AUTO == pullStyle) {
            ((InternalListView)getRefreshableView()).setAddedFooter(true);
        } else {
            ((InternalListView)getRefreshableView()).setAddedFooter(false);
        }
    }

    public void setEventSource(EventSource eventSource) {
        switch (eventSource) {
            case AUTO:
                break;
            case MANUAL:
                setOnLastItemVisibleListener(null);
                break;
        }
    }

    public void setLoadMore() {
        loadMoreLayout.setState(LoadMoreLayout.State.STATE_DEFAULT);
    }

    public void setLoadingMore() {
        loadMoreLayout.setState(LoadMoreLayout.State.STATE_LOADING);
    }

    public void setLoadNoData() {
        loadMoreLayout.setState(LoadMoreLayout.State.STATE_NO_DATA);
    }

    public LoadMoreLayout getLoadMoreLayout() {
        return loadMoreLayout;
    }

    public LoadingLayout getLoadingLayout(){
        return mHeaderLoadingView;
    }
    public void addFootView() {
        try {
            if (removeFootView()) {
                getRefreshableView().addFooterView(loadMoreLayout);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean removeFootView() {
        try {
            getRefreshableView().removeFooterView(loadMoreLayout);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public void removeFootListener(){
        setOnLoadMoreListener(null);
        setOnLastItemVisibleListener(null);
    }

    @Override
    public final Orientation getPullToRefreshScrollDirection() {
        return Orientation.VERTICAL;
    }

    @Override
    protected void onRefreshing(final boolean doScroll) {
        /**
         * If we're not showing the Refreshing view, or the list is empty, the
         * the header/footer views won't show so we use the normal method.
         */
        ListAdapter adapter = mRefreshableView.getAdapter();
        if (!mListViewExtrasEnabled || !getShowViewWhileRefreshing() || null == adapter || adapter.isEmpty()) {
            super.onRefreshing(doScroll);
            return;
        }

        super.onRefreshing(false);

        final LoadingLayout origLoadingView, listViewLoadingView, oppositeListViewLoadingView;
        final int selection, scrollToY;

        switch (getCurrentMode()) {
            case MANUAL_REFRESH_ONLY:
            case PULL_FROM_END:
                origLoadingView = getFooterLayout();
                listViewLoadingView = mFooterLoadingView;
                oppositeListViewLoadingView = mHeaderLoadingView;
                selection = mRefreshableView.getCount() - 1;
                scrollToY = getScrollY() - getFooterSize();
                //listScrollToY= 0;
                break;
            case PULL_FROM_START:
            default:
                Log.i("fyh","PULL_FROM_START");
                origLoadingView = getHeaderLayout();
                listViewLoadingView = mHeaderLoadingView;
                oppositeListViewLoadingView = mFooterLoadingView;
                selection = 0;
                Log.i("fyh","getHeaderSize()="+getHeaderSize());
                scrollToY = getScrollY() + getHeaderSize();
                //listScrollToY = -getHeaderSize();
                break;
        }

        // Hide our original Loading View
        if (null != listViewLoadingView) {
            origLoadingView.reset();
            origLoadingView.hideAllViews();
        } else {
            origLoadingView.refreshing();
        }

        // Make sure the opposite end is hidden too
        oppositeListViewLoadingView.setVisibility(GONE);

        // Show the ListView Loading View and set it to refresh.
        if (null != listViewLoadingView) {
            listViewLoadingView.setVisibility(VISIBLE);
            listViewLoadingView.refreshing();
        }

        if (doScroll) {
            // We need to disable the automatic visibility changes for now
            disableLoadingLayoutVisibilityChanges();

            // We scroll slightly so that the ListView's header/footer is at the
            // same Y position as our normal header/footer
            if (null != listViewLoadingView) {
                setHeaderScroll(scrollToY);
            }

            // Make sure the ListView is scrolled to show the loading
            // header/footer
            mRefreshableView.setSelection(selection);

            // Smooth scroll as normal
            smoothScrollTo(0);
        }
    }

    @Override
    protected void onReset() {
        /**
         * If the extras are not enabled, just call up to super and return.
         */
        if (!mListViewExtrasEnabled) {
            super.onReset();
            return;
        }

        final LoadingLayout originalLoadingLayout, listViewLoadingLayout;
        final int scrollToHeight, selection;
        final boolean scrollLvToEdge;

        switch (getCurrentMode()) {
            case MANUAL_REFRESH_ONLY:
            case PULL_FROM_END:
                originalLoadingLayout = getFooterLayout();
                listViewLoadingLayout = mFooterLoadingView;
                selection = mRefreshableView.getCount() - 1;
                scrollToHeight = getFooterSize();
                scrollLvToEdge = Math.abs(mRefreshableView.getLastVisiblePosition() - selection) <= 1;
                break;
            case PULL_FROM_START:
            default:
                originalLoadingLayout = getHeaderLayout();
                listViewLoadingLayout = mHeaderLoadingView;
                scrollToHeight = -getHeaderSize();
                selection = 0;
                scrollLvToEdge = Math.abs(mRefreshableView.getFirstVisiblePosition() - selection) <= 1;
                break;
        }

        // If the ListView header loading layout is showing, then we need to
        // flip so that the original one is showing instead
        if (listViewLoadingLayout.getVisibility() == VISIBLE) {

            // Set our Original View to Visible
            originalLoadingLayout.showInvisibleViews();

            // Hide the ListView Header/Footer
            listViewLoadingLayout.setVisibility(GONE);

            /**
             * Scroll so the View is at the same Y as the ListView
             * header/footer, but only scroll if: we've pulled to refresh, it's
             * positioned correctly
             */
            if (scrollLvToEdge && getState() != State.MANUAL_REFRESHING) {
                mRefreshableView.setSelection(selection);
                setHeaderScroll(scrollToHeight);
            }
        }

        // Finally, call up to super
        super.onReset();
    }

    @Override
    protected LoadingLayoutProxy createLoadingLayoutProxy(final boolean includeStart, final boolean includeEnd) {
        LoadingLayoutProxy proxy = super.createLoadingLayoutProxy(includeStart, includeEnd);

        if (mListViewExtrasEnabled) {
            final Mode mode = getMode();

            if (includeStart && mode.showHeaderLoadingLayout()) {
                proxy.addLayout(mHeaderLoadingView);
            }
            if (includeEnd && mode.showFooterLoadingLayout()) {
                proxy.addLayout(mFooterLoadingView);
            }
        }

        return proxy;
    }

    protected ListView createListView(Context context, AttributeSet attrs) {
        final ListView lv;
        if (VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD) {
            lv = new InternalListViewSDK9(context, attrs);
        } else {
            lv = new InternalListView(context, attrs);
        }
        return lv;
    }

    @Override
    protected ListView createRefreshableView(Context context, AttributeSet attrs) {
        ListView lv = createListView(context, attrs);
        // Set it to this so it can be used in ListActivity/ListFragment
        lv.setId(android.R.id.list);
        return lv;
    }

    @Override
    protected void handleStyledAttributes(TypedArray a) {
        super.handleStyledAttributes(a);

        mListViewExtrasEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrListViewExtrasEnabled, true);

        if (mListViewExtrasEnabled) {
            final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);

            // CreateOrder Loading Views ready for use later
            FrameLayout frame = new FrameLayout(getContext());
            mHeaderLoadingView = createLoadingLayout(getContext(), Mode.PULL_FROM_START, a);
            mHeaderLoadingView.setVisibility(GONE);
            frame.addView(mHeaderLoadingView, lp);
            mRefreshableView.addHeaderView(frame, null, false);
            mLvFooterLoadingFrame = new FrameLayout(getContext());
            mFooterLoadingView = createLoadingLayout(getContext(), Mode.PULL_FROM_END, a);
            mFooterLoadingView.setVisibility(GONE);
            mLvFooterLoadingFrame.addView(mFooterLoadingView, lp);

            /**
             * If the value for Scrolling While Refreshing hasn't been
             * explicitly set via XML, enable Scrolling While Refreshing.
             */
            if (!a.hasValue(R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled)) {
                setScrollingWhileRefreshingEnabled(true);
            }
        }
    }

    @TargetApi(9)
    final class InternalListViewSDK9 extends InternalListView {

        public InternalListViewSDK9(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override
        protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX,
                                       int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {

            final boolean returnValue = super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX,
                    scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);

            // Does all of the hard work...
            OverscrollHelper.overScrollBy(PullToRefreshLocationListView.this, deltaX, scrollX, deltaY, scrollY, isTouchEvent);

            return returnValue;
        }
    }
    public interface OnSizeChangedListener {
        public void onSizeChanged();
    }


    public class InternalListView extends ListView implements EmptyViewMethodAccessor {
        private OnSizeChangedListener onSizeChangedListener;
        public void setOnSizeChangedListener(OnSizeChangedListener onSizeChangedListener) {
            this.onSizeChangedListener = onSizeChangedListener;
        }
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            onSizeChangedListener.onSizeChanged();
        }

        private boolean mAddedLvFooter = false;

        public void setAddedFooter(boolean added) {
            mAddedLvFooter = added;
            addFooterView();
        }

        public InternalListView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            /**
             * This is a bit hacky, but Samsung's ListView has got a bug in it
             * when using Header/Footer Views and the list is empty. This masks
             * the issue so that it doesn't cause an FC. See Issue #66.
             */
            try {
                super.dispatchDraw(canvas);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            /**
             * This is a bit hacky, but Samsung's ListView has got a bug in it
             * when using Header/Footer Views and the list is empty. This masks
             * the issue so that it doesn't cause an FC. See Issue #66.
             */
            try {
                return super.dispatchTouchEvent(ev);
            } catch (Throwable e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        public void setAdapter(ListAdapter adapter) {
            // Add the Footer View at the last possible moment
            addFooterView();
            super.setAdapter(adapter);
        }

        public void addFooterView() {
            if (null != mLvFooterLoadingFrame && !mAddedLvFooter) {
                try {
                    removeFooterView(mLvFooterLoadingFrame);
                } catch (Throwable e) {
                    BallLog.e(TAG, "addFooterView e[" + e + "]");
                }
                try {
                    addFooterView(mLvFooterLoadingFrame, null, false);
                } catch (Throwable e) {
                    BallLog.e(TAG, "addFooterView e[" + e + "]");
                }
                mAddedLvFooter = true;
            }
        }

        @Override
        public void setEmptyView(View emptyView) {
            PullToRefreshLocationListView.this.setEmptyView(emptyView);
        }

        @Override
        public void setEmptyViewInternal(View emptyView) {
            super.setEmptyView(emptyView);
        }
    }
}
